﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Bussines;

namespace ownx
{
    public partial class wfCalendar : System.Web.UI.Page
    {
        int pUserID = -1;
        TBLObj pBLObj;
        clCalendar _clCalendar;
        clTIPUS_LIST _clTipusok;
        clDayObjectList pDays;        
        DateTime DFrom;
        DateTime DTo;
        clUser _clUser;
        DateTime CurrDate;

        protected void Page_Load(object sender, EventArgs e)
        {
            TBLObj blObj = null;
            if (Session["BL"] != null)
            {
                blObj = (TBLObj)Session["BL"];
            }             
            pBLObj = blObj;

            _clCalendar = new clCalendar(blObj);
            _clUser = new clUser(blObj);
            _clTipusok = new clTIPUS_LIST(blObj, "TRV");
            pDays = new clDayObjectList();


            if (Session["USR_ID"] != null)
            {
                try
                {
                    pUserID = (int)Session["USR_ID"];
                }
                catch
                {
                    pUserID = -1;
                }
            }
            else
            {
                pUserID = -1;
            }           

            if (!IsPostBack)
            {
                if (Session["SELECTED_DATE"] != null)
                {
                    CurrDate = Convert.ToDateTime(Session["SELECTED_DATE"]);
                }
                else
                {
                    CurrDate = DateTime.Now;
                }

                lCurrentDate.Text = CurrDate.ToString("yyyy.MM.dd hh:mm");

                BuildControls();
                dpYear.SelectedValue = CurrDate.ToString("yyyy");
                dpMonth.SelectedValue = CurrDate.ToString("MM");
                FillWeekCombo();
                DateTime DD = GetFirstDayOfWeek(CurrDate);
                dpWeek.SelectedValue = GetFirstDayOfWeek(CurrDate).ToString("yyyy.MM.dd");               
                lState.Text = "BROWSE";
                lID.Text = "-1";
                lLastLoadedID.Text = "-1";
                lMessage.Text="";                
            }

            FillCombos();

            if (rbMonthly.Checked)
            {
                rb_CheckedChanged(rbMonthly, null);
            }
            if (rbWeekly.Checked)
            {
                rb_CheckedChanged(rbWeekly, null);
            }               
        }

        private void FillCombos()
        {
            dlTipus.Items.Clear();
            foreach (clTIPUS akt in _clTipusok.lTIPUS)
            {
                ListItem li = new ListItem(akt.fTPS_MEGNEVEZES, akt.fTPS_TIPUSKOD.ToString());
                dlTipus.Items.Add(li);
            }            
        }

        protected void rb_CheckedChanged(object sender, EventArgs e)
        {   
            if (sender == rbWeekly)
            {
                ShowWeeklyView();
            }
            if (sender == rbMonthly)
            {
                ShowMonthlyView();
            }            
        }       

        protected void ShowWeeklyView()
        {
            dpWeek.Visible = true;
            dpYear.Visible = false;
            dpMonth.Visible = false;          

            HtmlTableRow TR;
            TR = tbView.Rows[1];
            for (int I = 1; I <= TR.Cells.Count - 1; I++)
            {
                TR.Cells[I].Visible = true;
            }

            DFrom = DateTime.Parse(dpWeek.SelectedValue);
            string CurDate = DFrom.ToString("yyyy.MM.dd");

            DFrom = GetFirstDayOfWeek(DFrom);

            DTo = DFrom.AddDays(6);
            DateTime D = DFrom;
            DateTime TD = DFrom;            
            ListBox LB;
            Button B;            

            pDays.DayObjects.Clear();
                        
            for (int J = 0; J <= 6; J++)
            {
             //   TR.Cells[J].Height = "100%";
                LB = GetListBox(J, 1);
                LB.Style["height"] = "350px";
               // LB.Style["width"] = "90px";
                B = GetButton(J, 1);
                B.Text = TD.Day.ToString();

               
                //if (J == 5 || J == 6)
                //{
                //    TR.Cells[J].BgColor = "red";
                //    TR.Cells[J].Style["color"] = "white";
                //}
                ////mai nap
                //if (TD.ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd"))
                //{
                //    TR.Cells[J].BgColor = "green";
                //    TR.Cells[J].Style["color"] = "white";
                //}
                //hétvége
                if (J == 5 || J == 6)
                {
                    B.BackColor = System.Drawing.Color.Red;
                    B.ForeColor = System.Drawing.Color.White;
                }
                //mai nap
                if (TD.ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd"))
                {
                    B.BackColor = System.Drawing.Color.Green;
                    B.ForeColor = System.Drawing.Color.White;
                }

                if (!(J == 5 || J == 6) && !(TD.ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd")))
                {
                    B.BackColor = System.Drawing.Color.Black;
                    B.ForeColor = System.Drawing.Color.Yellow;
                }

                pDays.DayObjects.Add(new clDayObject(J, 1, TD, LB, B, TR.Cells[J]));
                TD = TD.AddDays(1);
            }

            for (int I = 2; I <= tbView.Rows.Count - 1; I++)
            {
                tbView.Rows[I].Visible = false;

            }
            tbView.Rows[1].Height = "300";
            //feltöltés
            if (!IsPostBack || lStartDate.Text != DFrom.ToString("yyyy.MM.dd"))
            {
                GetAllData();
                try
                {
                    TD = DateTime.Parse(lCurrentDate.Text);
                    clDayObject O = pDays.GetDay(TD);
                    LB = O.ListBox as ListBox;
                    LBSelectedIndexChanged(LB, null);
                }
                catch
                { }
            }
            lStartDate.Text = DFrom.ToString("yyyy.MM.dd");
        }

        protected void ShowMonthlyView()
        {
            dpWeek.Visible = false;
            dpYear.Visible = true;
            dpMonth.Visible = true;          

            HtmlTableRow TR;
            TR = tbView.Rows[1];
            for (int I = 1; I <= TR.Cells.Count - 1; I++)
            {
                TR.Cells[I].Visible = true;
            }

            DFrom = DateTime.Parse(dpYear.Text + "." + dpMonth.Text + ".01");
            string CurDate = DFrom.ToString("yyyy.MM.dd");

            DTo = DFrom.AddMonths(1).AddDays(-1);
            DateTime D = DFrom;
            DateTime TD;

            int Index = Convert.ToInt32(D.DayOfWeek);
            if (Index == 0)
            {
                Index = 7;
            }
            int DayCount = Index + System.DateTime.DaysInMonth(D.Year, D.Month);
            int RowC = (DayCount / 7);
            if (DayCount % 7 > 0)
            {
                RowC++;
            }
            
            ListBox LB;
            Button B;
            int K;
            
            TD = D.AddDays(-(Index - 1));

            pDays.DayObjects.Clear();
            tbView.Rows[1].Height = "60";
            for (int I = 1; I <= 5; I++)
            {                
                TR = tbView.Rows[I];
                TR.Visible = true;
                K = TD.Month;
                if (K == 12 && dpMonth.Text=="01")                
                {
                    K = 0;
                }
                if (K<=Convert.ToInt32( dpMonth.Text))
                {
                    for (int J = 0; J <= 6; J++)
                    {
                        LB = GetListBox(J, I);                  
                        B = GetButton(J, I);
                        B.Text = TD.Day.ToString();
                        LB.Style["height"] = "40px";
                        //hétvége
                        if (J == 5 || J == 6)
                        {                          
                            B.BackColor = System.Drawing.Color.Red;
                            B.ForeColor = System.Drawing.Color.White;
                        }
                        //mai nap
                        if (TD.ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd"))
                        {                          
                            B.BackColor = System.Drawing.Color.Green;
                            B.ForeColor = System.Drawing.Color.White;
                        }
                        if (!(J == 5 || J == 6) && !(TD.ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd")))
                        {
                            B.BackColor = System.Drawing.Color.Black;
                            B.ForeColor = System.Drawing.Color.Yellow;
                        }


                        pDays.DayObjects.Add(new clDayObject(J, I, TD, LB, B, TR.Cells[J]));
                        TD = TD.AddDays(1);
                    }
                }
                else
                {
                    TR.Visible = false;
                }
            }
           
            //feltöltés
            if (!IsPostBack || lStartDate.Text != DFrom.ToString("yyyy.MM.dd"))
            {
                GetAllData();
                try
                {
                    TD = DateTime.Parse(lCurrentDate.Text);
                    clDayObject O = pDays.GetDay(TD);
                    LB = O.ListBox as ListBox;                   
                    LBSelectedIndexChanged(LB, null);
                    lbDay.SelectedIndex = 0;
                    lbDay_SelectedIndexChanged(lbDay, null);
                }
                catch
                { 
                }
            }
            lStartDate.Text = DFrom.ToString("yyyy.MM.dd");
        }   

        void FillWeekCombo()
        {
            dpWeek.Items.Clear();
            int iMax = -1;
            DateTime DFrom = DateTime.Parse(dpYear.Text + ".01.01");         
            while (Convert.ToInt32(DFrom.DayOfWeek) > 1)
            {
                DFrom = DFrom.AddDays(-1);
            }
            DateTime DTo = DateTime.Parse(dpYear.Text + ".12.31");
            while (Convert.ToInt32(DTo.DayOfWeek) > 1)
            {                
                DTo = DTo.AddDays(1);
                if (iMax < Convert.ToInt32(DTo.DayOfWeek))
                {
                    iMax = Convert.ToInt32(DTo.DayOfWeek);
                }
            }

            DateTime D = DFrom;            
            string S;
            string Z;
            int J=1;
            while (D<=DTo)
            {
                Z = D.ToString("yyyy.MM.dd");                
                S = J.ToString() + ". hét (" + Z + " - ";
                for (int I = 1; I <= 7; I++)
                {
                    D = D.AddDays(1);
                }
                S = S+D.ToString("yyyy.MM.dd") + ")";
                dpWeek.Items.Add(new ListItem(S,Z));
                J++;
            }
        }

        void FillDayCombo()
        {
            dlDay.Items.Clear();
            int pMax = 30;
            int M = DFrom.Month;
            if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12)
            {
                pMax = 31;
            }
            if (M == 2)
            {
                if (DFrom.Year % 4 == 0 && DFrom.Year % 400 != 0)
                {
                    pMax = 29;
                }
                else
                {
                    pMax = 28;
                }
            }
            for (int I = 1; I <= pMax; I++)
            {
                dlDay.Items.Add(new ListItem(I.ToString("D2"), I.ToString("D2")));
            }
        }

        void SetDayList(DateTime iDay)
        {
            lbDay.Items.Clear();
            string pText = "";
            string pValue = "";
            DateTime D1 = iDay;
            DateTime D2 = D1.AddDays(1);
            DataSet DS = _clCalendar.GetData(D1,D2,pBLObj.USR_ID);
            if (DS.Tables[0].Rows.Count > 0)
            {
                //DateTime D;
                foreach (DataRow DR in DS.Tables[0].Rows)
                {
                    pText = DR["TRV_NEV"].ToString() + "," + DR["TRV_HELYSZIN"].ToString();
                    pValue = DR["TRV_ID"].ToString();
                    lbDay.Items.Add(new ListItem(pText, pValue));
                }
            }
            else
            {
                lbDay.Items.Add(new ListItem("üres", "-1"));
            }
        }

        void SetEdits(int iID)
        {
            bool Ures = false;
            lMessage.Text = "";
            if (iID > -1)
            {
                DataSet DS = _clCalendar.GetData(iID);
                if (DS.Tables[0].Rows.Count > 0)
                {
                    DateTime D;
                    foreach (DataRow DR in DS.Tables[0].Rows)
                    {      
                        DataSet US =_clUser.GetUser(Convert.ToInt16(DR["TRV_CREATED_BY"].ToString()));

                        tbName.Text = DR["TRV_NEV"].ToString();
                        tbLocation.Text = DR["TRV_HELYSZIN"].ToString();
                        D = Convert.ToDateTime(DR["TRV_IDOPONT"]);
                        dlYear.Text = D.ToString("yyyy");
                        dlMonth.Text = D.ToString("MM");
                        dlDay.Text = D.ToString("dd");
                        dlHour.Text = D.ToString("hh");
                        dlMinute.Text = D.ToString("mm");
                        tbComment.Text = DR["TRV_MEGJEGYZES"].ToString();
                        dlDone.SelectedValue = DR["TRV_LETREJOTT"].ToString();
                        lID.Text = DR["TRV_ID"].ToString();
                        lLastLoadedID.Text = DR["TRV_ID"].ToString();
                        lState.Text = "MODIFY";

                        lUsr.Text = US.Tables[0].Rows[0]["USR_NAME"].ToString();


                    }
                }
                else
                {
                    Ures = true;
                }
            }
            else
            {
                Ures = true;
            }

            if (Ures)
            {             
                tbName.Text = "";
                tbLocation.Text = "";
                DateTime D = DateTime.Parse(lCurrentDate.Text);
                dlYear.Text = D.ToString("yyyy");
                dlMonth.Text = D.ToString("MM");
                if (Convert.ToInt32(dlDay.Items[dlDay.Items.Count - 1].Value) >= D.Day)
                {
                    dlDay.Text = D.ToString("dd");
                }
                else
                {
                    dlDay.Text = dlDay.Items[dlDay.Items.Count - 1].Value;
                }
                dlHour.Text = D.ToString("hh");
                dlMinute.Text = "00";
                tbComment.Text = "";
                dlDone.SelectedValue = "N";
                lState.Text = "NEW";
                lID.Text = "-1";
                lUsr.Text = "";
                if (iID != -2)
                {
                    lLastLoadedID.Text = "-1";
                }                
            }
            SignSelectedDay();
        }

        void SignSelectedDay()
        {
            DateTime D;
            try
            {
                D = DateTime.Parse(lCurrentDate.Text);
                clDayObject C = pDays.GetDay(D);
                if (C != null)
                {
                    if ((C.Button as Button).Parent != null)
                    {
                        //((C.Button as Button).Parent as HtmlTableCell).BgColor = "blue";
                        //((C.Button as Button).Parent as HtmlTableCell).Style["color"] = "white";
                        (C.Button as Button).ForeColor = System.Drawing.Color.White;
                        (C.Button as Button).Font.Bold = true;
                        (C.Button as Button).Font.Size = FontUnit.Small;
                        (C.Button as Button).BorderWidth = 1;
                        (C.Button as Button).BorderColor = System.Drawing.Color.DarkGray;

                    }
                }
            }
            catch { }
        }

        void UnSignSelectedDay()
        {
            DateTime D;
            HtmlTableCell TC;
            HtmlTableRow TR;
            Button B;
            int J = -1;
            try
            {
                D = DateTime.Parse(lCurrentDate.Text);
                clDayObject C = pDays.GetDay(D);
                if (C != null)
                {                    
                    B = (C.Button as Button);
                    TC = B.Parent as HtmlTableCell;
                    TR = TC.Parent as HtmlTableRow;
                    if (TC != null)
                    {
                        for (int I = 0; I < TR.Cells.Count - 1; I++)
                        {
                            if (TR.Cells[I] == TC)
                            {
                                J = I;
                                break;
                            }
                        }

                        (C.ListBox as ListBox).SelectedIndex = -1;

                        //hétvége
                        if (J == 5 || J == 6)
                        {
                            B.BackColor = System.Drawing.Color.Red;
                            B.ForeColor = System.Drawing.Color.White;
                        }
                        else
                        {
                            //mai nap
                            if (B.Text == DateTime.Now.Day.ToString())
                            {
                                B.BackColor = System.Drawing.Color.Green;
                                B.ForeColor = System.Drawing.Color.White;
                            }
                            else
                            {
                                B.BackColor = System.Drawing.Color.Black;
                                B.ForeColor = System.Drawing.Color.Yellow;                                
                            }
                        }
                        B.Font.Bold = false;
                        B.Font.Size = FontUnit.Small;
                        B.BorderWidth = 0;
                        B.BorderColor = System.Drawing.Color.DarkSlateGray;
                    }
                }
            }
            catch { }
        }


        void GetAllData()
        {
            DataSet DS;
            clDayObject O;
            ListBox LB;
            string pText;
            string pValue;
            foreach (clDayObject O1 in pDays.DayObjects)
            {
                if ((O1.Cell as HtmlTableCell).Parent.Visible)
                {
                    (O1.ListBox as ListBox).Items.Clear();
                    (O1.ListBox as ListBox).Items.Add(new ListItem("üres", "-1"));
                }
            }

            DS = _clCalendar.GetData(DFrom, DTo.AddDays(1),pBLObj.USR_ID);
            if (DS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow DR in DS.Tables[0].Rows)
                {
                    O = pDays.GetDay(Convert.ToDateTime(DR["TRV_IDOPONT"]).Date);
                    if (O != null && (O.Cell as HtmlTableCell).Parent.Visible)
                    {
                        if ((O.ListBox as ListBox).Items[0].Text == "üres")
                        {
                            (O.ListBox as ListBox).Items.Clear();
                        }
                        pText = DR["TRV_NEV"].ToString() + "," + DR["TRV_HELYSZIN"].ToString();
                        pValue = DR["TRV_ID"].ToString();
                        LB = O.ListBox as ListBox;
                        LB.Items.Add(new ListItem(pText, pValue));
                    }
                }
            }
        }

        void BuildControls()
        {
            pDays = new clDayObjectList();
            for (int I = 1; I <= 6; I++)
            {
                for (int J = 1; J <= 7; J++)
                {                    
                    ListBox LB;
                    LB = new ListBox();
                    LB.Style["Width"] = "100%";
                    LB.Style["Height"] = "auto";
                    LB.AutoPostBack = true;                 
                }
            }
        }
       
        ListBox GetListBox(int X,int Y)
        {
            ListBox LB=null;
            HtmlTableCell C = tbView.Rows[Y].Cells[X];
            foreach (Control O in C.Controls)
            {               
                if (O.GetType()==typeof(ListBox))
                {
                    LB = O as ListBox;
                    break;
                }
            }
            return LB;
        }

        DateTime GetDateByLB(ListBox iLB)
        {
            foreach (clDayObject O in pDays.DayObjects)
            {
                if ((O.ListBox as ListBox).ID == iLB.ID)
                {
                    return O.Day;                    
                }
            }
            return DateTime.MinValue;
        }

        DateTime GetDateByB(Button iB)
        {
            foreach (clDayObject O in pDays.DayObjects)
            {
                if ((O.Button as Button).ID == iB.ID)
                {
                    return O.Day;
                }
            }
            return DateTime.MinValue;
        }
        
        Button GetButton(int X, int Y)
        {
            Button B = null;
            HtmlTableCell C = tbView.Rows[Y].Cells[X];
            foreach (Control O in C.Controls)
            {
                if (O.GetType() == typeof(Button))
                {
                    B = O as Button;
                    break;
                }
            }
            return B;
        }

        Button GetButton(ListBox iLB)
        {
            Button B = null;
            HtmlTableCell C = iLB.Parent as HtmlTableCell;
            if (C != null)
            {
                foreach (Control O in C.Controls)
                {
                    if (O.GetType() == typeof(Button))
                    {
                        B = O as Button;
                        break;
                    }
                }                
            }
            return B;
        }

        protected void DayButtonClick(object sender, EventArgs e)
        {
            Button B = sender as Button;
            DateTime D=GetDateByB(B);
            string S;

            S = D.ToString("yyyy.MM.dd hh:mm");
           
            if (lCurrentDate.Text != S)
            {
                UnSignSelectedDay();
            }
            lCurrentDate.Text = S;

            SetDayList(D);
            lbDay.SelectedIndex = 0;
            lbDay_SelectedIndexChanged(lbDay, new EventArgs());
        }

        protected void LBSelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox LB = sender as ListBox;
            DateTime D=GetDateByLB(LB);
            string S=D.ToString("yyyy.MM.dd hh:mm");
                       
            if (lCurrentDate.Text != S)
            {
                UnSignSelectedDay();
            }
            lCurrentDate.Text = S;

            int ID = -1;
            try
            {
                if (LB.SelectedIndex != -1)
                {
                    ID = Convert.ToInt32(LB.Items[LB.SelectedIndex].Value);
                }
            }
            catch
            {
            }

            SetDayList(D);
            lbDay.SelectedIndex = LB.SelectedIndex;
            SetEdits(ID);            
        }

        protected void btNew_Click(object sender, EventArgs e)
        {            
            SetEdits(-2);   
        }

        protected void btCancel_Click(object sender, EventArgs e)
        {            
            SetEdits(Convert.ToInt32(lLastLoadedID.Text));
        }

        protected void btSave_Click(object sender, EventArgs e)
        {      
            lMessage.Text="";
            if (tbName.Text == "")
            {
                lMessage.Text += "név,";
            }
            if (tbLocation.Text == "")
            {
                lMessage.Text += "helyszín,";
            }

            if (lMessage.Text != "")
            {
                lMessage.Text = "Hiányos adatok! (" + lMessage.Text;
                if (lMessage.Text.EndsWith(","))
                {
                    lMessage.Text = lMessage.Text.Substring(1, lMessage.Text.Length - 1);
                }
                lMessage.Text += ")";
            }
            else
            {
                if (lID.Text == "-1")
                {
                    string Err = "";
                    DateTime D = DateTime.Parse(dlYear.SelectedValue + "." + dlMonth.SelectedValue + "." + dlDay.SelectedValue + " " + dlHour.SelectedValue + ":" + dlMinute.SelectedValue);
                    if (!_clCalendar.InsertTerv(tbName.Text, tbLocation.Text, D, tbComment.Text, dlDone.SelectedValue, ref Err))
                    {
                        lMessage.Text = Err;                    
                    }
                    else
                    {
                        SetEdits(Convert.ToInt32(lID.Text));
                    }
                }
                else
                {
                    string Err = "";
                    DateTime D = DateTime.Parse(dlYear.SelectedValue + "." + dlMonth.SelectedValue + "." + dlDay.SelectedValue + " " + dlHour.SelectedValue + ":" + dlMinute.SelectedValue);
                    if (!_clCalendar.UpdateTerv(lID.Text, tbName.Text, tbLocation.Text, D, tbComment.Text, dlDone.SelectedValue, ref Err))
                    {
                        lMessage.Text = Err;                     
                    }
                    else
                    {
                        SetEdits(Convert.ToInt32(lID.Text));
                    }
                }

                GetAllData();
            }            
        }

        protected void btDelete_Click(object sender, EventArgs e)
        {
            string Err = "";
            if (!_clCalendar.DeleteTerv(lID.Text, ref Err))
            {
                lMessage.Text = Err;             
            }
            else
            {                
                SetEdits(Convert.ToInt32(lID.Text));
                GetAllData();
            }
        }

        protected void btBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("wfDefault.aspx");
        }

        DateTime GetFirstDayOfWeek(DateTime iD)
        {
            DateTime D = iD;
            int I = Convert.ToInt32(D.DayOfWeek);
            
            if (I == 0)
            {
                I = 7;
            }
            D = D.AddDays(-(I-1));
            
            return D;
        }

        protected void lbDay_SelectedIndexChanged(object sender, EventArgs e)
        {        
            ListBox LB = sender as ListBox;            

            int ID = -1;
            try
            {
                if (LB.SelectedIndex != -1)
                {
                    ID = Convert.ToInt32(LB.Items[LB.SelectedIndex].Value);
                }
            }
            catch
            {
            }

            SetEdits(ID);                    
        }

        protected void btPartner_Click(object sender, EventArgs e)
        {
            try
            {
                int I = Convert.ToInt32(lID.Text);
                int PRTID;
                string Err = "";
                PRTID=_clCalendar.GeneratePartner(I, ref Err);
                lMessage.Text = Err;
                Session["PRT_ID"] = PRTID;
                Session["PARENT_FORM"] = "wfCalendar.aspx";
                Response.Redirect("wfPartner.aspx");
            }
            catch
            {
                lMessage.Text = "Hibás TRV_ID!";
            }
        }
    }
}
